package com.kexilo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

/**
 * Kexilo应用启动监听器
 * 
 * @author Kexilo
 */
public class KexiloApplicationListener implements ApplicationListener<ApplicationEvent> {
    
    private static final Logger log = LoggerFactory.getLogger(KexiloApplicationListener.class);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationStartingEvent) {
            handleApplicationStarting();
        } else if (event instanceof ApplicationReadyEvent) {
            handleApplicationReady((ApplicationReadyEvent) event);
        } else if (event instanceof ContextClosedEvent) {
            handleApplicationClosed();
        }
    }

    /**
     * 应用启动中
     */
    private void handleApplicationStarting() {
        log.info("===== Kexilo权限管理系统启动中 =====");
        log.info("正在初始化Spring容器...");
        
        // 检查运行环境
        checkRuntime();
    }

    /**
     * 应用启动完成
     */
    private void handleApplicationReady(ApplicationReadyEvent event) {
        log.info("===== Kexilo权限管理系统启动完成 =====");
        
        String port = event.getApplicationContext().getEnvironment().getProperty("server.port", "8080");
        String contextPath = event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path", "");
        
        log.info("应用端口：{}", port);
        log.info("上下文路径：{}", contextPath);
        log.info("API文档地址：http://localhost:{}{}/swagger-ui.html", port, contextPath);
        log.info("健康检查：http://localhost:{}{}/actuator/health", port, contextPath);
        log.info("应用指标：http://localhost:{}{}/actuator/metrics", port, contextPath);
        
        // 输出启动耗时
        long startupTime = System.currentTimeMillis() - event.getTimestamp();
        log.info("启动耗时：{}ms", startupTime);
        
        // 输出系统信息
        printSystemInfo();
    }

    /**
     * 应用关闭
     */
    private void handleApplicationClosed() {
        log.info("===== Kexilo权限管理系统正在关闭 =====");
        log.info("正在清理资源...");
        log.info("应用已安全关闭");
    }

    /**
     * 检查运行环境
     */
    private void checkRuntime() {
        // 检查Java版本
        String javaVersion = System.getProperty("java.version");
        log.info("Java版本：{}", javaVersion);
        
        // 检查内存配置
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory() / 1024 / 1024;
        long totalMemory = runtime.totalMemory() / 1024 / 1024;
        long freeMemory = runtime.freeMemory() / 1024 / 1024;
        
        log.info("JVM内存配置 - 最大：{}MB, 总计：{}MB, 可用：{}MB", maxMemory, totalMemory, freeMemory);
        
        // 内存不足警告
        if (maxMemory < 512) {
            log.warn("⚠️  JVM最大内存小于512MB，建议增加内存配置：-Xmx1024m");
        }
    }

    /**
     * 输出系统信息
     */
    private void printSystemInfo() {
        log.info("===== 系统信息 =====");
        log.info("操作系统：{} {}", System.getProperty("os.name"), System.getProperty("os.version"));
        log.info("Java版本：{}", System.getProperty("java.version"));
        log.info("用户目录：{}", System.getProperty("user.dir"));
        log.info("时区：{}", System.getProperty("user.timezone"));
        
        // 输出可用处理器数
        int processors = Runtime.getRuntime().availableProcessors();
        log.info("可用处理器：{}核", processors);
        
        log.info("==================");
    }
}
